package com.biluo.mvs.ui.activity

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Error
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.biluo.mvs.MainActivity
import com.biluo.mvs.model.VehicleOwner
import com.biluo.mvs.network.VehicleOwnerApi
import com.biluo.mvs.utils.GlobalData
import com.biluo.mvs.utils.Utils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {
	private lateinit var shared: SharedPreferences
	@Inject lateinit var userApi: VehicleOwnerApi

	override fun onCreate(savedInstanceState: Bundle?) {
		// 初始化binding
		super.onCreate(savedInstanceState)
		shared = getSharedPreferences("user", MODE_PRIVATE)
		val id = shared.getString("id", "")!!
		val password = shared.getString("password", "")!!
		setContent {
			MaterialTheme { loginScreen(id, password) }
		}
	}

	@Composable
	fun loginScreen(originId: String, originPwd: String) {
		val ID_REGEX = Regex("^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$")
		val PWD_REGEX = Regex("^[a-zA-Z\\d]{4,16}$")
		val scope = rememberCoroutineScope()

		var id by remember { mutableStateOf(originId) }
		var password by remember { mutableStateOf(originPwd) }
		var idErrorMsg by remember { mutableStateOf("") }
		var pwdErrorMsg by remember { mutableStateOf("") }

		var checked by remember { mutableStateOf(false) }

		fun checkIdFormat(): Boolean {
			idErrorMsg = if (id.isEmpty()) "身份证号不能为空" else {
				if (!ID_REGEX.matches(id)) "身份证号格式错误" else ""
			}
			return idErrorMsg.isEmpty()
		}

		fun checkPwdFormat(): Boolean {
			pwdErrorMsg = if (password.isEmpty()) "密码不能为空" else {
				if (!PWD_REGEX.matches(password)) "密码必须由4-16位的字母或数字组成" else ""
			}
			return pwdErrorMsg.isEmpty()
		}

		suspend fun login() {
			if (!checkIdFormat() || !checkPwdFormat()) return
			Utils.handleResp(userApi.login(VehicleOwner(id, password)), "token") {
				GlobalData.token = it.toString()
				// 如果选择了记住用户，将身份证号和密码写入sharePreferences
				if (checked) {
					shared.edit().putString("id", id).apply()
					shared.edit().putString("password", password).apply()
				} else {
					shared.edit().remove("id").apply()
					shared.edit().remove("password").apply()
				}
				// 登录成功，然后跳转到主页
				Utils.showToast("登录成功")
				val intent = Intent(this, MainActivity::class.java)
				intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
				this.startActivity(intent)
			}
		}

		Column(modifier = Modifier.padding(16.dp)) {
			TextField(  // 身份证输入框
				value = id,
				onValueChange = { id = it },
				label = { Text("身份证号") },
				placeholder = { Text("请输入身份证号") },
				isError = idErrorMsg.isNotEmpty(),
				trailingIcon = {
					if (idErrorMsg.isNotEmpty()) {    // 如果有错误提示，则显示错误图标
						Icon(Icons.Filled.Error, contentDescription = "Error")
					}
				},
				supportingText = { Text(idErrorMsg) },    // 显示在下方的错误提示
				modifier = Modifier.fillMaxWidth()
				/*.onFocusChanged { focusState -> // 进入页面时会直接显示错误提示，不友好；改为点击登录时再检查格式
                if (!focusState.isFocused) {
                    idErrorMsg = if (id.isEmpty()) "身份证号不能为空" else {
                        if (!ID_REGEX.matches(id)) "身份证号格式错误" else ""
                    }
                }
            }*/
			)
			TextField(  // 密码输入框
				value = password,
				onValueChange = { password = it },
				label = { Text("密码") },
				placeholder = { Text("请输入密码") },
				isError = pwdErrorMsg.isNotEmpty(),
				trailingIcon = {
					if (pwdErrorMsg.isNotEmpty()) {    // 如果有错误提示，则显示错误图标
						Icon(Icons.Filled.Error, contentDescription = "Error")
					}
				},
				supportingText = { Text(pwdErrorMsg) },    // 显示在下方的错误提示
				modifier = Modifier.fillMaxWidth().padding(top = 4.dp)
			)
			Row(
				verticalAlignment = Alignment.CenterVertically, // 行内元素垂直居中
				horizontalArrangement = Arrangement.spacedBy((-6).dp),  // 行内元素间距
				modifier = Modifier.clickable(
					interactionSource = remember { MutableInteractionSource() },
					indication = null   // 移除点击效果
				) { // 点击整个 Row 切换选中状态
					checked = !checked
				}
			) {
				Checkbox(checked = checked, onCheckedChange = { checked = it })
				Text("记住用户")
			}
			Button(
				onClick = { scope.launch { login() }},
				modifier = Modifier.fillMaxWidth()
			) {
				Text("登     录")
			}
		}
	}
}